package com.itqf.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/9/23
 * @Time: 下午3:22
 */
public class MyBatisUtils {

    final  static ThreadLocal<SqlSession> sessionThreadLocal = new ThreadLocal<>();

   static   SqlSessionFactory sqlSessionFactory = null;

    static{
            try {
            //1.读mybatis的配置文件  返回InputStream
            InputStream inputStream =  Resources.getResourceAsStream("mybatisConfig.xml");
            //2.SqlSessionFactory   SessionFactory(hibernate)
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //3.SqlSession    Connection   Session(hibernate)
              //sqlSession = sqlSessionFactory.openSession();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }



    public static SqlSession getSqlSession(){
       SqlSession sqlSession = sessionThreadLocal.get();
       if (sqlSession==null){
           sqlSession = sqlSessionFactory.openSession();
           //存储到ThreadLocal
           sessionThreadLocal.set(sqlSession);
       }

       return  sqlSession;
    }


    public  static void commit(){
        getSqlSession().commit();
        close();
    }

    public static  void close(){
        SqlSession s = getSqlSession();
        s.close();
        sessionThreadLocal.remove();//移除存储的值
    }

    public static  void  rollback(){
        SqlSession s = getSqlSession();
        s.rollback();
    }

    // List<?>
    public  static  <T extends  Object> T  getMapper(Class<T> tClass){
      return   getSqlSession().getMapper(tClass);
    }

   public  static  void  main(String[]args){

       System.out.println(getSqlSession().getConnection());//同一个线程得到的SqlSession是唯一的



   }



}
